package com.ywk.transactional.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 两种编程式事务编程案例
 * @Author zbh
 * @Date 2025/3/16
 */
@Component
public class UserService {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    PlatformTransactionManager transactionManager;
    @Autowired
    TransactionTemplate transactionTemplate;


    /**
     * transactionManager 实现编程式事物
     */
    public void transfer1() {
        //定义默认的食物属性
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        //获取 transactionStatus
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
        try {
            jdbcTemplate.update("update tb_student set age = ? where id = 25",20);
            int i = 1/0;
        }catch (DataAccessException e){
            transactionManager.rollback(transactionStatus);
            throw e;
        }
        transactionManager.commit(transactionStatus);
    }

    /**
     * transactionTemplate 实现编程式事务
     */
    public void transfer2() {
        transactionTemplate.execute(status -> {
            try {
                jdbcTemplate.update("update tb_student set age = ? where id = 25",20);
                int i = 1/0;
            }catch (DataAccessException e){
                status.setRollbackOnly();
                throw e;
            }
            return null;
        });
    }


}
